import { useEmitter } from 'src/emitter';
import { onMounted, onUnmounted, ref, watchEffect } from 'vue';

export const useVersion = () => {
  const outdated = ref(false);
  useEmitter('websocket', payload => {
    if (payload.data === 'EV_WEB_VERSION') {
      outdated.value = true;
    }
  });

  watchEffect(() => {
    if (outdated.value && document.visibilityState === 'visible') {
      location.reload();
    }
  });

  const handler = () => {
    if (outdated.value && document.visibilityState === 'visible') {
      location.reload();
    }
  };
  onMounted(() => {
    document.addEventListener('visibilitychange', handler);
  });
  onUnmounted(() => {
    document.removeEventListener('visibilitychange', handler);
  });
};
